package ltd.hyangyang.vegetable.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import ltd.hyangyang.vegetable.entity.ClassificationEntity;
import ltd.hyangyang.vegetable.entity.History;
import ltd.hyangyang.vegetable.mapper.ClassificationMapper;
import ltd.hyangyang.vegetable.service.ClassificationService;
import ltd.hyangyang.vegetable.service.HistoryService;
import ltd.hyangyang.vegetable.utils.PageUtils;
import ltd.hyangyang.vegetable.utils.ScriptUtils;
import ltd.hyangyang.vegetable.utils.TestProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.io.File;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;
import java.util.stream.Collectors;

@Service
public class ClassificationServiceImpl extends ServiceImpl<ClassificationMapper, ClassificationEntity> implements ClassificationService {
    private ExecutorService executorService = Executors.newFixedThreadPool(10);

    @Autowired
    private HistoryService historyService;

    @Autowired
    private TestProperties testProperties;

    @Override
    public ClassificationEntity distinguish(String dirPath, String fileName) {
        //根据目录和文件名称来得到分类名和分类详情
        Integer classificationIndex = getDistinguishResult(dirPath, fileName);
        //根据index下标查询水果种类及相关信息
        ClassificationEntity classificationEntity = getById(classificationIndex);

        executorService.submit(()->{
            //将计算的结果保存到数据库中
            Integer parentId = classificationEntity.getParentId();
            ClassificationEntity classification = getById(parentId);
            History history = new History();
            history.setHistoryId(classification.getClassId());
            history.setClassLabel(classification.getClassLabel());
            history.setCreateTime(LocalDateTime.now());
            historyService.save(history);
        });

        return classificationEntity;
    }

    public Integer getDistinguishResult(String dirPath,String fileName){
        String filePath = testProperties.getTestDirPath() + File.separator + fileName;
        String[] args = {"python", testProperties.getUseScriptPath(), filePath, testProperties.getModelUsePath()};
        String classificationIndexStr = ScriptUtils.runScript(args);
        if (StringUtils.isEmpty(classificationIndexStr)) {
            return null;
        }
        Integer classificationIndex = Integer.parseInt(classificationIndexStr);
        return classificationIndex;
    }

    @Override
    public Page<ClassificationEntity> getAll(ClassificationEntity classification) {
        Page<ClassificationEntity> page = PageUtils.getPage();
        QueryWrapper<ClassificationEntity> classificationEntityQueryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(classification.getClassLabel())) {
            classificationEntityQueryWrapper.like("class_label", classification.getClassLabel());
        }
        classificationEntityQueryWrapper.ge("class_id",0);

        Page<ClassificationEntity> classificationEntityPage = this.page(page, classificationEntityQueryWrapper);
        return classificationEntityPage;
    }

    @Override
    public List<ClassificationEntity> getAllList() {
        QueryWrapper<ClassificationEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.ge("class_id",0);
        List<ClassificationEntity> classificationEntities = this.baseMapper.selectList(queryWrapper);
        return classificationEntities;
    }

    @Override
    public List<ClassificationEntity> categoryTree() {
        List<ClassificationEntity> classificationEntities = this.baseMapper.selectList(null);
        Map<Integer, List<ClassificationEntity>> classificationMap = new HashMap<>();
        List<ClassificationEntity> parentClassificationList = new ArrayList<>();
        classificationEntities.stream().forEach(classification -> {
            if (classification.getParentId() == null&&classification.getClassId()<0) {
                parentClassificationList.add(classification);
            }
            List<ClassificationEntity> classificationList = classificationMap.get(classification.getParentId());
            if (CollectionUtils.isEmpty(classificationList)) {
                classificationList = new ArrayList<>();

            }
            classificationList.add(classification);
            classificationMap.put(classification.getParentId(), classificationList);
        });

        //创建一个键为Label的Map
        List<ClassificationEntity> parentClassificationEntityList = parentClassificationList.stream().map(parentClassification->{
            Integer classId = parentClassification.getClassId();
            List<ClassificationEntity> classificationList = classificationMap.get(classId);
            parentClassification.setChild(classificationList);
            return parentClassification;
        }).collect(Collectors.toList());
        return parentClassificationEntityList;
    }

    @Override
    public List<ClassificationEntity> search(String keyword) {
        QueryWrapper<ClassificationEntity> queryWrapper = new QueryWrapper<>();
        //可以是在classLabel，或者scientific_name，或者purpose中存在
        queryWrapper.
                like("class_label",keyword)
                .or()
                .like("scientific_name",keyword)
                .or().like("purpose",keyword);

        List<ClassificationEntity> classificationEntities = this.baseMapper.selectList(queryWrapper);
        return classificationEntities;
    }

    @Override
    public Integer getDistinguishId(String dirPath, String fileName) {
        return getDistinguishResult(dirPath,fileName);
    }
}
